from typing import Optional, Dict, List
class AutocompleteLanguageInfo:
    def __init__(self, name: str, top_level_keywords: List[str], comment: str):
        self.name = name
        self.top_level_keywords = top_level_keywords
        self.comment = comment

LANGUAGES: Dict[str, AutocompleteLanguageInfo] = {
    'py': AutocompleteLanguageInfo("Python", [
        "def", "import", "from", "class", "return", "yield", "try", "except", "with", "lambda", "assert", "async", "await", "global"
    ], "#"),
    
    'js': AutocompleteLanguageInfo("JavaScript", [
        "function", "const", "let", "var", "return", "class", "import", "export", "if", "else", "for", "while", "try", "catch", "await", "async", "new"
    ], "//"),
    
    'ts': AutocompleteLanguageInfo("TypeScript", [
        "interface", "type", "export", "class", "public", "private", "protected", "readonly", "extends", "implements", "function", "let", "const", "declare", "module"
    ], "//"),
    
    'java': AutocompleteLanguageInfo("Java", [
        "class", "import", "package", "public", "private", "protected", "static", "void", "extends", "implements", "new", "return", "try", "catch", "synchronized", "interface", "super", "final", "abstract"
    ], "//"),
    
    'cpp': AutocompleteLanguageInfo("C++", [
        "#include", "namespace", "template", "class", "public", "private", "protected", "virtual", "new", "delete", "return", "try", "catch", "for", "if", "else", "void", "int", "const", "static", "using"
    ], "//"),
    
    'rs': AutocompleteLanguageInfo("Rust", [
        "fn", "let", "mut", "struct", "impl", "enum", "use", "mod", "match", "if", "else", "return", "pub", "crate", "const", "static", "trait", "new"
    ], "//"),
}


class LanguageDetector:
    @staticmethod
    def detect_from_content(code: str) -> Optional[AutocompleteLanguageInfo]:
        scores = {lang: 0 for lang in LANGUAGES.keys()}
        
        for lang, language_info in LANGUAGES.items():
            for keyword in language_info.top_level_keywords:
                if keyword in code:
                    scores[lang] += 1

        best_match = max(scores.items(), key=lambda x: x[1])
        return LANGUAGES[best_match[0]]

def format_snippet(snippet: str, filename = None):
    language = LanguageDetector.detect_from_content(snippet)
    comment = language.comment
    lines = [
        f"{comment} Below is a code snippet" if filename is None else f"{comment} the below code fragment can be found in {filename}",
        *[f"{comment} {line}" for line in snippet.strip().split("\n")],
        comment,
    ]
    return "\n".join(lines)





